﻿@{
    ViewBag.Title = "Pages";
    Layout = "~/Views/Shared/_Layout_Administration.cshtml";
}

<div class="row">
    <div class="span4">
        <ul class="container empty-item" data-bind="sortableList: { tmpl: 'newSitePageDefinitionTmpl', list: newSitePageDefinition }">
        </ul>
    </div>
    <div class="span4">
        <div class="alert alert-info">
            Drag this to page groups to create new page.
            For creating page with url like "www.site.com/NewPage", drag new page to page group named "root".           
        </div>
    </div>
</div>

<hr class="soften">

<div id="main">
<div class="preloader preloader-page-groups"></div>
<ul class="unstyled page-groups hide" data-bind="foreach: pageGroup">
    <li>
        <div class="row">
            <div class="span0 delete-page-group pointer">
                <i data-bind="click: $parent.removePageGroup, visible: GroupName()!='root'" class="icon-remove"></i>
                <span class="btn btn-primary create-page-group" data-bind="click: $parent.addPageGroup, visible: GroupName()=='root'"><span>+</span></span>
            </div>
            @Html.ValidationSummary(true, "Please correct the errors and try again.")
            <div class="span4">
                <h2>/<span class="pointer editor-min-width-height" data-bind="text: GroupName, click: function() { if($data.GroupName()=='root') return;  self.selectPageGroup($data); }, visible: $data !== self.selectedPageGroup()"></span>
                    <input type="text" placeholder="Type page group name…" class="input-big page-group-name-input" data-bind="value: GroupName, visibleAndSelect: $data === self.selectedPageGroup(), event: { blur: function() { self.selectPageGroup(''); } }" />/</h2>
                    <span class="validationMessage" data-bind="visible: GroupName.hasError, text: GroupName.validationMessage"> </span>
            </div>
            <div class="span5 site-page-definition">
                <ul class="container span4 unstyled site-page-definition-ul" data-bind="sortableList: { tmpl: 'sitePageDefinitionTmpl', list: SitePageDefinition }">
                </ul>
            </div>
        </div>
    </li>
</ul>

<button class="btn btn-danger" data-bind="click: loadDataFromServer">Discard all changes</button>
<button class="btn btn-success" data-bind="click: save">Save all changes</button>    
</div>

@* modal dialof *@
<div id="dialogEditModal" class="fade modal" style="display: none; ">
    <div class="modal-header">
        <a href="#" class="close" data-bind="click: self.closeSitePageEditDialog">&times;</a>
        <h3>Site page editing</h3>
    </div>
    <div class="modal-body">
        <div class="divDialogElements">
            <div class="modal-editing">
                <table class="hide-on-cb-showing">
                    <tr>
                        <td>Internal description:</td>
                        <td class="intr-descr-2-col" colspan="4">
                            <textarea placeholder="Type smth…" class="" rows='4' cols='90' data-bind="value: self.editingPageGroupDefinition.InternalDescription()">
            </textarea></td>
                    </tr>
                    <tr>
                        <td>Is active:</td>
                        <td>
                            <input type="checkbox" data-bind="checked: self.editingPageGroupDefinition.IsActive()" />
                        </td>
                        <td><div class="spacer-150"></div></td>
                         <td>Sort order:</td>
                        <td class="text-align-right">
                            <input class="width-50" type="number" data-bind="value: self.editingPageGroupDefinition.SortOrder()" />
                        </td>
                    </tr>
                </table>

                <div class="tabbable">
                    <ul class="nav nav-tabs hide-on-cb-showing" id="editing-pages-dialog-tabs">
                        <!-- ko foreach: self.editingPageGroupDefinition.SitePage() -->
                        <li><a data-toggle="tab" data-bind="attr: { href: '#pb'+Id()()}"><span data-bind="text: CultureInfo()()"></span></a></li>
                        <!-- /ko -->
                    </ul>
                    <div class="tab-content" id="editing-pages-dialog-content">
                        <!-- ko foreach: self.editingPageGroupDefinition.SitePage() -->
                        <div class="tab-pane" data-bind="attr: {id: 'pb'+Id()()}">
                            <table class="hide-on-cb-showing">
                                <tr>
                                    <td>Title:</td>
                                    <td class="intr-descr-2-col">
                                        <input placeholder="Type title…" type="text" data-bind="value: Title()" />
                                    </td>
                                </tr>
                                <tr>
                                    <td>MetaName</td>
                                    <td class="intr-descr-2-col">
                                        <input placeholder="Type meta name…" type="text" data-bind="value: MetaName()" />
                                    </td>
                                </tr>
                                <tr>
                                    <td>MetaKeyword</td>
                                    <td class="intr-descr-2-col">
                                        <input placeholder="Type meta keywords…" type="text" data-bind="value: MetaKeywords()" />
                                    </td>
                                </tr>
                            </table>
                            <div class="content-blocks-editing-hide">
                                <a class="btn" data-bind="event: { click: self.hideContentBlock}">Back to upper</a>
                            </div>
                            <div class="content-blocks-editing-switch" data-bind="foreach: ContentBlock()">
                                <a class="btn" data-bind="event: { click: self.showContentBlock},text: 'Edit '+CBDInternalName"></a>
                            </div>
                            <div class="margin15" data-bind="foreach: ContentBlock()">
                                 <div  class="content-blocks-editing" data-bind="attr: {id: 'cb'+Id()()}"}>
                                <textarea class="content-blocks-editing-textarea"  data-bind="tinymce: HTMLContent(), tinymceOptions: { theme: 'advanced', width: 680, height: 350, }"></textarea>                                   
                                    </div>
                            </div>
                        </div>
                        <!-- /ko -->
                    </div>

                </div>
            </div>

        </div>
    </div>
    <div class="modal-footer">
        <a href="#" class="btn primary" data-bind="click: self.closeSitePageEditDialog">OK</a>
        <a href="#" class="btn secondary" data-bind="click: self.closeSitePageEditDialog">Cancel</a>
    </div>
</div>

@section scripts{  

    <script id="sitePageDefinitionTmpl" type="text/html">
        <li class="site-page-definition-li">
            <table>
                <tr>
                    <td>
                        <h3 class="span4" ><span class="pointer editor-min-width-height" style="min-width:50px; min-height:30px;" data-bind="text: InternalName, click: function() { self.selectPageGroupDefinition($data); }, visible: $data !== self.selectedPageGroupDefinition()"></span>
                            <input type="text" placeholder="Type page name…" class="input-big" data-bind="value: InternalName, visibleAndSelect: $data === self.selectedPageGroupDefinition(), event: { blur: function() { self.selectPageGroupDefinition(''); } }" />
                     <br />
                             <span class="validationMessage" data-bind="visible: InternalName.hasError, text: InternalName.validationMessage"> </span>
                        </h3>
                    </td>
                    <td>
                        <i data-bind="click: function() { self.openSitePageEditDialog($data); }" class="icon-edit pointer"></i>
                    </td>
                </tr>
            </table>
        </li>
    </script>

    <script id="newSitePageDefinitionTmpl" type="text/html">
        <li>
            <h3><span class="pointer" data-bind="text: InternalName"></span>
            </h3>
        </li>
    </script>
      
    <script type="text/javascript">

       

        function ContentBlockDefinition(data) {
            this.Id = ko.observable(data.Id);
            this.InternalName = ko.observable(data.InternalName);
        }

        function PageGroup(data) {
            this.Id = ko.observable(data.Id);
            this.GroupName = ko.observable(data.GroupName).extend({ required: "", urlElement: "" });
            this.SitePageDefinition = ko.observableArray([]);
            if (data.SitePageDefinition != null) {
                var mappedSitePageDefinition = $.map(data.SitePageDefinition, function (item) { return new SitePageDefinition(item) });
                this.SitePageDefinition(mappedSitePageDefinition);
            }
            else {
                //some code maybe
            }
        }

        function SitePageDefinition(data) {
            this.Id = ko.observable(data.Id);
            this.InternalDescription = ko.observable(data.InternalDescription);
            this.InternalName = ko.observable(data.InternalName).extend({ required: "", urlElement: "" });
            this.IsActive = ko.observable(data.IsActive);
            this.SortOrder = ko.observable(data.SortOrder);
            if (data.SitePage != null) {
                var mappedSitePage = $.map(data.SitePage, function (item) { return new SitePage(item) });
                this.SitePage = ko.observableArray([]);
                this.SitePage(mappedSitePage);
            }
            else {
                this.SitePage = ko.observableArray([]);
                for (var i = 0; i < self.languages().length; i++) {
                    this.SitePage.push(new SitePage({ Id: 0, Title: "New Page", CultureInfo: self.languages()[i].Name }));
                }
            }
        }

        function SitePage(data) {
            this.Id = ko.observable(data.Id);
            this.Title = ko.observable(data.Title);
            this.MetaName = ko.observable(data.MetaName);
            this.MetaKeywords = ko.observable(data.MetaKeywords);
            this.CultureInfo = ko.observable(data.CultureInfo);

            var isFunc = jQuery.isFunction(data.ContentBlock);

            this.ContentBlock = ko.observableArray([]);
            if (data.ContentBlock != null) {
                if (!isFunc) {
                    var mappedContentBlock = $.map(data.ContentBlock, function (item) { return new ContentBlock(item) });
                    this.ContentBlock(mappedContentBlock);
                }
                else {
                    var mappedContentBlock = $.map(data.ContentBlock(), function (item) { return new ContentBlock(item) });
                    this.ContentBlock(mappedContentBlock);
                }
            }

            else {

                for (var i = 0; i < self.contentBlockDefinitions().length; i++) {
                    this.ContentBlock.push(new ContentBlock({ Id: -i, CBDInternalName: self.contentBlockDefinitions()[i].InternalName(), CBDId: self.contentBlockDefinitions()[i].Id(), HTMLContent: 'type smth...' }));
                }


            }
        }

        function ContentBlock(data) {
            this.Id = ko.observable(data.Id);
            this.HTMLContent = ko.observable(data.HTMLContent);
            if (data.ContentBlockDefinition != null) {
                this.CBDInternalName = data.ContentBlockDefinition.InternalName;
                this.ContentBlockDefinitionId = data.ContentBlockDefinition.Id;
            }
            else {
                // hacks
                var smallHack = data.CBDInternalName;
                var smallHack2 = data.CBDId;
                this.CBDInternalName = smallHack;
                this.ContentBlockDefinitionId = smallHack2;
            }
        }

        var self;
               
        function PageGroupListViewModel() {
            // Data
            self = this;
            self.languages = ko.observableArray([]);
            self.contentBlockDefinitions = ko.observableArray([]);
            self.pageGroup = ko.observableArray([]);



            self.newSitePageDefinition = ko.observableArray([]);

            self.selectedPageGroup = ko.observable();
            self.selectPageGroup = function (pageGroup) {
                this.selectedPageGroup(pageGroup);
            };

            self.selectedPageGroupDefinition = ko.observable();
            self.selectPageGroupDefinition = function (pageGroupDefinition) {
                this.selectedPageGroupDefinition(pageGroupDefinition);
            };

            // Operations
            self.addPageGroup = function () {
                self.pageGroup.push(new PageGroup({ Id: 0, GroupName: "NewGroup" }));
            };

            self.addPageGroupDefinition = function () {
                self.newSitePageDefinition.push(new SitePageDefinition({ Id: 0, InternalName: "NewPage" }));
            };

            self.removePageGroup = function (PageGroup) {
                self.pageGroup.remove(PageGroup);
            };

            self.editingPageGroupDefinition = ko.observable();
            self.editingPageGroupDefinition.InternalName = ko.observable();
            self.editingPageGroupDefinition.InternalDescription = ko.observable();
            self.editingPageGroupDefinition.IsActive = ko.observable();
            self.editingPageGroupDefinition.SortOrder = ko.observable();
            self.editingPageGroupDefinition.SitePage = ko.observableArray([]);

            self.openSitePageEditDialog = function (pageGroupDefinition) {
                self.editingPageGroupDefinition.InternalName(pageGroupDefinition.InternalName);
                self.editingPageGroupDefinition.InternalDescription(pageGroupDefinition.InternalDescription);
                self.editingPageGroupDefinition.IsActive(pageGroupDefinition.IsActive);
                self.editingPageGroupDefinition.SortOrder(pageGroupDefinition.SortOrder);

                var mappedSitePage = $.map(pageGroupDefinition.SitePage(), function (item) { return new SitePage(item) });
                self.editingPageGroupDefinition.SitePage(mappedSitePage);

                var modalDialog = $("#dialogEditModal");

                var browserName = navigator.appName;
                if (browserName == 'Microsoft Internet Explorer' && modalDialog.hasClass("fade")) {
                    modalDialog.removeClass("fade");
                }

                $("#editing-pages-dialog-tabs li:first", modalDialog).addClass("active");
                $("#editing-pages-dialog-content div:first", modalDialog).addClass("active");

                $(".hide-on-cb-showing").show('slow', function () {
                });

                $('.content-blocks-editing-hide').hide();
                $('.content-blocks-editing').hide();
                $('.content-blocks-editing-switch a').removeClass('btn-primary');

                modalDialog.modal({ show: true });

            };



            self.closeSitePageEditDialog = function () {
                $("#dialogEditModal").modal('hide');
            };

            self.showContentBlock = function (contentBlock) {

                $('.content-blocks-editing-switch a').removeClass('btn-primary');

                $(window.event.srcElement).addClass('btn-primary');

                $('.content-blocks-editing').hide();

                $(".hide-on-cb-showing").hide('slow', function () {
                    $('#cb' + contentBlock.Id()()).show();
                    needToShow = false;
                });

                $('.content-blocks-editing-hide').show();

            };

            self.hideContentBlock = function () {
                $('.content-blocks-editing-switch a').removeClass('btn-primary');
                $(".hide-on-cb-showing").show('slow', function () {
                });

                $('.content-blocks-editing-hide').hide();
                $('.content-blocks-editing').hide();

            };

            self.save = function () {
                if (!HasErrors()) {       
                    TogglePreloader('.preloader-page-groups', '.page-groups');
                    $.ajax("SetPageGroups", {
                        data: ko.toJSON({ SitePageGroups: self.pageGroup }),
                        type: "post", contentType: "application/json",
                        success: function (result) { alert(result); TogglePreloader('.preloader-page-groups', '.page-groups'); }
                    });
                }                
            };

            // Load initial state from server, convert it to PageGroup instances, then populate self.pageGroup
            self.loadDataFromServer = function () {
                $.getJSON("GetPageGroups", function (allData) {
                    var mappedpageGroup = $.map(allData, function (item) { return new PageGroup(item) });
                    self.pageGroup(mappedpageGroup);

                    TogglePreloader('.preloader-page-groups', '.page-groups');
                });
            };

            self.loadContentBlockDefinitionsFromServer = function () {
                $.getJSON("GetContentBlockDefinitions", function (allData) {
                    var mappedContentBlockDefinitions = $.map(allData, function (item) { return new ContentBlockDefinition(item) });
                    self.contentBlockDefinitions(mappedContentBlockDefinitions);
                    self.loadDataFromServer();
                    self.addPageGroupDefinition();
                });
            }

            self.loadLanguagesListFromServer = function () {
                $.getJSON("GetLanguages", function (allData) {
                    var mappedLanguages = $.map(allData, function (item) { return new Language(item) });
                    self.languages(mappedLanguages);

                    if (self.contentBlockDefinitions().length == 0);
                    {
                        self.loadContentBlockDefinitionsFromServer();
                    }
                });

            };


            self.loadLanguagesListFromServer();

        }

        ko.applyBindings(new PageGroupListViewModel());

    </script>

}